document.addEventListener('DOMContentLoaded', function() {
  // 初始化变量
  let roseChart = null;
  let matrixChart = null; // 添加散点图矩阵变量
  let chartData = []; // 存储所有数据
  let types = []; // 存储所有分类类型
  let currentType = 'all'; // 当前选中的类型
  
  // 颜色方案
  const colorPalette = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#FEC89A', '#B5838D',
    '#84A59D', '#F28482', '#7BDFF2', '#F9DC5C', '#A2D2FF',
    '#AE76A6', '#99C1B9', '#FFAFCC', '#7D80DA', '#FFD166'
  ];
  
  // 创建更鲜艳的统一颜色方案
  const matrixColorPalette = [
    '#FF3366', /* 鲜红色 */
    '#33CCFF', /* 天蓝色 */
    '#FFCC00', /* 金黄色 */
    '#66CC33', /* 草绿色 */
    '#9966FF'  /* 紫色 */
  ];
  
  // 为每个图表创建不同的颜色方案
  const matrixColorPalette1 = ['#FF3366', '#FF6699', '#FF99CC', '#FFCCFF', '#FF0033']; // 红色系
  const matrixColorPalette2 = ['#33CCFF', '#66FFFF', '#99FFFF', '#00CCFF', '#0099CC']; // 蓝色系
  const matrixColorPalette3 = ['#FFCC00', '#FFFF00', '#FFCC33', '#FF9900', '#FF6600']; // 黄色系
  const matrixColorPalette4 = ['#66CC33', '#99FF66', '#CCFF99', '#33CC00', '#009933']; // 绿色系
  
  // 初始化图表
  function initChart() {
    if (roseChart) {
      roseChart.dispose();
    }
    
    roseChart = echarts.init(document.getElementById('roseChart'));
    
    // 加载Excel数据
    loadExcelData();
    
    // 窗口大小变化时调整图表大小
    window.addEventListener('resize', function() {
      if (roseChart) {
        roseChart.resize();
      }
      if (matrixChart) {
        matrixChart.resize();
      }
    });
    
    // 初始化散点图矩阵
    initMatrixChart();
  }
  
  // 初始化散点图矩阵
  function initMatrixChart() {
    if (matrixChart) {
      matrixChart.dispose();
    }
    
    matrixChart = echarts.init(document.getElementById('matrixChart'));
    
    // 加载散点图矩阵数据
    loadMatrixData();
  }
  
  // 加载散点图矩阵数据
  function loadMatrixData() {
    fetch('../static/json/life-expectancy-table.json')
      .then(response => {
        if (!response.ok) {
          throw new Error('网络错误');
        }
        return response.json();
      })
      .then(data => {
        renderMatrixChart(data);
      })
      .catch(error => {
        console.error('加载散点图数据失败:', error);
        // 使用模拟数据
        const mockData = generateMockData();
        renderMatrixChart(mockData);
      });
  }
  
  // 生成模拟数据（用于加载真实数据失败时）
  function generateMockData() {
    const countries = ['中国', '美国', '日本', '英国', '德国', '法国', '加拿大', '澳大利亚'];
    const years = ['2020', '2021', '2022'];
    const mockData = [];
    
    for (let country of countries) {
      for (let year of years) {
        mockData.push({
          'Income': Math.round(Math.random() * 50000 + 10000),
          'Life Expectancy': Math.round(Math.random() * 30 + 50),
          'Population': Math.round(Math.random() * 1000000000),
          'Country': country,
          'Year': year
        });
      }
    }
    
    return mockData;
  }
  
  // 渲染散点图矩阵
  function renderMatrixChart(data) {
    if (!matrixChart) return;
    
    // 调整网格间距，给图表更多空间
    const sizeValue = '60%';
    const symbolSize = 3.5; // 增大点的尺寸
    
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: '二手商品多维度分析矩阵',
        left: 'center',
        top: 0,
        textStyle: {
          color: '#f9fafb',
          fontSize: 18
        }
      },
      legend: {
        top: 30,
        textStyle: {
          color: '#f9fafb'
        }
      },
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(0, 40, 58, 0.9)',
        borderColor: 'rgba(255, 255, 255, 0.3)',
        textStyle: {
          color: '#f9fafb'
        },
        formatter: function(params) {
          return `
            <div style="font-weight:bold;margin-bottom:5px;">${params.data.Country} (${params.data.Year})</div>
            <div>价格: ${params.data.Income.toLocaleString()} 元</div>
            <div>使用年限: ${params.data.Life_Expectancy || params.data['Life Expectancy']} 年</div>
            <div>数量: ${params.data.Population.toLocaleString()} 件</div>
          `;
        }
      },
      toolbox: {
        left: 'center',
        top: 30,
        itemSize: 15,
        feature: {
          dataZoom: {},
          restore: {}
        },
        iconStyle: {
          color: '#f9fafb',
          borderColor: '#f9fafb'
        }
      },
      grid: [
        { right: '55%', bottom: sizeValue, top: '20%', left: '8%' },
        { left: '55%', bottom: sizeValue, top: '20%', right: '8%' },
        { right: '55%', top: sizeValue, bottom: '20%', left: '8%' },
        { left: '55%', top: sizeValue, bottom: '20%', right: '8%' }
      ],
      xAxis: [
        {
          type: 'value',
          gridIndex: 0,
          name: '价格(元)',
          nameLocation: 'middle',
          nameGap: 25,
          nameTextStyle: {
            color: '#f9fafb',
            fontSize: 12,
            padding: [10, 0, 0, 0]
          },
          axisLabel: { 
            color: '#f9fafb',
            rotate: 30,
            formatter: function(value) {
              return value >= 10000 ? (value/10000) + '万' : value;
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        },
        {
          type: 'category',
          gridIndex: 1,
          name: '品类',
          nameLocation: 'end',
          nameGap: 15,
          nameTextStyle: {
            color: '#f9fafb',
            fontSize: 12,
            align: 'right'
          },
          axisLabel: { 
            color: '#f9fafb',
            interval: 0,
            rotate: 45
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        },
        {
          type: 'value',
          gridIndex: 2,
          name: '价格(元)',
          nameLocation: 'middle',
          nameGap: 25,
          nameTextStyle: {
            color: '#f9fafb',
            fontSize: 12,
            padding: [10, 0, 0, 0]
          },
          axisLabel: { 
            color: '#f9fafb',
            rotate: 30,
            formatter: function(value) {
              return value >= 10000 ? (value/10000) + '万' : value;
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        },
        {
          type: 'value',
          gridIndex: 3,
          name: '使用年限(年)',
          nameLocation: 'middle',
          nameGap: 25,
          nameTextStyle: {
            color: '#f9fafb',
            fontSize: 12,
            padding: [10, 0, 0, 0]
          },
          axisLabel: { 
            color: '#f9fafb'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        }
      ],
      yAxis: [
        { 
          type: 'value', 
          gridIndex: 0, 
          name: '使用年限(年)',
          nameLocation: 'end',
          nameTextStyle: {
            color: '#f9fafb',
            fontSize: 12,
            align: 'right',
            padding: [0, 10, 0, 0]
          },
          axisLabel: { color: '#f9fafb' },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        },
        { 
          type: 'value', 
          gridIndex: 1, 
          name: '价格(元)',
          nameLocation: 'end',
          nameTextStyle: {
            color: '#f9fafb',
            fontSize: 12,
            align: 'right',
            padding: [0, 10, 0, 0]
          },
          axisLabel: { 
            color: '#f9fafb',
            formatter: function(value) {
              return value >= 10000 ? (value/10000) + '万' : value;
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        },
        { 
          type: 'value', 
          gridIndex: 2, 
          name: '数量(件)',
          nameLocation: 'end',
          nameTextStyle: {
            color: '#f9fafb',
            fontSize: 12,
            align: 'right',
            padding: [0, 10, 0, 0]
          },
          axisLabel: { 
            color: '#f9fafb',
            formatter: function(value) {
              return value >= 10000 ? (value/10000) + '万' : value;
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        },
        { 
          type: 'value', 
          gridIndex: 3, 
          name: '数量(件)',
          nameLocation: 'end',
          nameTextStyle: {
            color: '#f9fafb',
            fontSize: 12,
            align: 'right',
            padding: [0, 10, 0, 0]
          },
          axisLabel: { 
            color: '#f9fafb',
            formatter: function(value) {
              return value >= 10000 ? (value/10000) + '万' : value;
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }
        }
      ],
      dataset: {
        dimensions: [
          'Income',
          'Life Expectancy',
          'Population',
          'Country',
          { name: 'Year', type: 'ordinal' }
        ],
        source: data
      },
      series: [
        {
          type: 'scatter',
          symbolSize: symbolSize,
          xAxisIndex: 0,
          yAxisIndex: 0,
          itemStyle: {
            color: function(params) {
              const countries = [...new Set(data.map(item => item.Country))];
              const countryIndex = countries.indexOf(params.data.Country);
              return matrixColorPalette1[countryIndex % matrixColorPalette1.length];
            }
          },
          emphasis: {
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(255, 255, 255, 0.5)'
            },
            scale: true
          },
          encode: {
            x: 'Income',
            y: 'Life Expectancy',
            tooltip: [0, 1, 2, 3, 4]
          }
        },
        {
          type: 'scatter',
          symbolSize: symbolSize,
          xAxisIndex: 1,
          yAxisIndex: 1,
          itemStyle: {
            color: function(params) {
              const countries = [...new Set(data.map(item => item.Country))];
              const countryIndex = countries.indexOf(params.data.Country);
              return matrixColorPalette2[countryIndex % matrixColorPalette2.length];
            }
          },
          emphasis: {
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(255, 255, 255, 0.5)'
            },
            scale: true
          },
          encode: {
            x: 'Country',
            y: 'Income',
            tooltip: [0, 1, 2, 3, 4]
          }
        },
        {
          type: 'scatter',
          symbolSize: symbolSize,
          xAxisIndex: 2,
          yAxisIndex: 2,
          itemStyle: {
            color: function(params) {
              const countries = [...new Set(data.map(item => item.Country))];
              const countryIndex = countries.indexOf(params.data.Country);
              return matrixColorPalette3[countryIndex % matrixColorPalette3.length];
            }
          },
          emphasis: {
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(255, 255, 255, 0.5)'
            },
            scale: true
          },
          encode: {
            x: 'Income',
            y: 'Population',
            tooltip: [0, 1, 2, 3, 4]
          }
        },
        {
          type: 'scatter',
          symbolSize: symbolSize,
          xAxisIndex: 3,
          yAxisIndex: 3,
          itemStyle: {
            color: function(params) {
              const countries = [...new Set(data.map(item => item.Country))];
              const countryIndex = countries.indexOf(params.data.Country);
              return matrixColorPalette4[countryIndex % matrixColorPalette4.length];
            }
          },
          emphasis: {
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(255, 255, 255, 0.5)'
            },
            scale: true
          },
          encode: {
            x: 'Life Expectancy',
            y: 'Population',
            tooltip: [0, 1, 2, 3, 4]
          }
        }
      ]
    };
    
    matrixChart.setOption(option);
    
    // 添加动画效果
    document.querySelector('.matrix-chart-container').classList.add('fade-in');
    setTimeout(() => {
      document.querySelector('.matrix-chart-container').classList.remove('fade-in');
    }, 500);
  }
  
  // 加载Excel数据
  function loadExcelData() {
    fetch('../static/csv/rank.xlsx')
      .then(response => {
        if (!response.ok) {
          throw new Error('网络错误');
        }
        return response.arrayBuffer();
      })
      .then(buffer => {
        const data = new Uint8Array(buffer);
        const workbook = XLSX.read(data, { type: 'array' });
        
        // 假设Excel的第一个工作表包含数据
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        
        // 将工作表转换为JSON
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        
        // 处理数据
        processData(jsonData);
      })
      .catch(error => {
        console.error('加载Excel文件失败:', error);
        // 使用模拟数据
        const mockData = [
          { title: '手机', num: 3580, type: '电子数码' },
          { title: '笔记本电脑', num: 2700, type: '电子数码' },
          { title: '平板电脑', num: 1820, type: '电子数码' },
          { title: '相机', num: 1450, type: '电子数码' },
          { title: '耳机', num: 980, type: '电子数码' },
          { title: '服装', num: 2850, type: '服饰箱包' },
          { title: '鞋帽', num: 1950, type: '服饰箱包' },
          { title: '手表', num: 1200, type: '服饰箱包' },
          { title: '箱包', num: 1680, type: '服饰箱包' },
          { title: '珠宝首饰', num: 890, type: '服饰箱包' },
          { title: '书籍', num: 2100, type: '文化娱乐' },
          { title: '游戏', num: 1750, type: '文化娱乐' },
          { title: '乐器', num: 620, type: '文化娱乐' },
          { title: '收藏品', num: 880, type: '文化娱乐' },
          { title: '办公桌椅', num: 750, type: '家居家装' },
          { title: '沙发', num: 680, type: '家居家装' },
          { title: '床垫', num: 520, type: '家居家装' },
          { title: '厨房用具', num: 950, type: '家居家装' },
          { title: '自行车', num: 1150, type: '运动户外' },
          { title: '健身器材', num: 870, type: '运动户外' },
          { title: '露营装备', num: 580, type: '运动户外' }
        ];
        processData(mockData);
      });
  }
  
  // 处理数据
  function processData(data) {
    chartData = data;
    
    // 提取所有类型
    types = [...new Set(data.map(item => item.type))];
    
    // 更新类型选择器
    updateTypeSelector();
    
    // 渲染图表
    renderChart(currentType);
    
    // 更新洞察信息
    updateInsights(data);
  }
  
  // 更新类型选择器
  function updateTypeSelector() {
    const selector = document.getElementById('typeSelect');
    selector.innerHTML = '<option value="all">全部分类</option>';
    
    types.forEach(type => {
      const option = document.createElement('option');
      option.value = type;
      option.textContent = type;
      selector.appendChild(option);
    });
    
    // 添加事件监听
    selector.addEventListener('change', function() {
      currentType = this.value;
      renderChart(currentType);
    });
  }
  
  // 渲染玫瑰图
  function renderChart(type) {
    if (!roseChart) return;
    
    // 筛选数据
    let filteredData = chartData;
    if (type !== 'all') {
      filteredData = chartData.filter(item => item.type === type);
    }
    
    // 按数量降序排序并限制显示数量
    filteredData = filteredData.sort((a, b) => b.num - a.num).slice(0, 15);
    
    // 计算总数
    const total = filteredData.reduce((sum, item) => sum + item.num, 0);
    
    // 图表配置
    const option = {
      backgroundColor: 'transparent',
      title: {
        text: type === 'all' ? '二手商品交易量分布' : `${type}类商品交易量分布`,
        left: 'center',
        top: 0,
        textStyle: {
          color: '#f9fafb'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          const percent = ((params.value / total) * 100).toFixed(1);
          return `${params.name}<br/>数量: ${params.value.toLocaleString()}<br/>占比: ${percent}%`;
        }
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: '5%',
        top: 'center',
        textStyle: {
          color: '#f9fafb'
        }
      },
      series: [
        {
          name: '交易量',
          type: 'pie',
          radius: ['20%', '70%'],
          center: ['40%', '50%'],
          roseType: 'area',
          itemStyle: {
            borderRadius: 8
          },
          data: filteredData.map((item, index) => ({
            name: item.title,
            value: item.num,
            itemStyle: {
              color: colorPalette[index % colorPalette.length]
            }
          })),
          label: {
            color: '#f9fafb'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            label: {
              fontWeight: 'bold',
              fontSize: 16
            }
          }
        }
      ]
    };
    
    // 应用配置
    roseChart.setOption(option);
    
    // 添加动画效果
    document.querySelector('.rose-chart-container').classList.add('fade-in');
    setTimeout(() => {
      document.querySelector('.rose-chart-container').classList.remove('fade-in');
    }, 500);
  }
  
  // 更新洞察信息
  function updateInsights(data) {
    // 按类型分组
    const typeGroups = {};
    data.forEach(item => {
      if (!typeGroups[item.type]) {
        typeGroups[item.type] = 0;
      }
      typeGroups[item.type] += item.num;
    });
    
    // 找出最热门类型
    let topType = '';
    let topValue = 0;
    for (const type in typeGroups) {
      if (typeGroups[type] > topValue) {
        topValue = typeGroups[type];
        topType = type;
      }
    }
    
    // 计算总数和百分比
    const total = data.reduce((sum, item) => sum + item.num, 0);
    const percentage = ((topValue / total) * 100).toFixed(1);
    
    // 更新DOM
    document.getElementById('topCategory').textContent = topType;
    document.getElementById('topPercentage').textContent = `${percentage}%`;
    
    // 生成趋势文本
    const trendTexts = [
      "环保意识提升，闲置物品再利用需求增长，二手交易逐年上升",
      `${topType}类商品在二手市场最受欢迎，成交速度快且保值率高`,
      "年轻用户是二手交易主力军，注重性价比和可持续消费理念",
      "移动互联网促进二手市场繁荣，线上交易平台成交量持续增长"
    ];
    
    document.getElementById('trendText').textContent = trendTexts[Math.floor(Math.random() * trendTexts.length)];
  }
  
  // 初始化
  initChart();
});
